<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"> 
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>WebSocket Chat</title>
</head>

<body>

<script type="text/javascript">
    var socket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
	function connect() {
		if (document.getElementById('btnconn').value==="断开") {
			disconnect();
		} else {
			var addreses = document.getElementById('address').value;
			var ta1 = document.getElementById('chatContent');
					ta1.value = "开始连接!"+addreses;
			// addreses = "ws://127.0.0.1:96/api/chat?name=xjh2&to=xjh1";
			if (window.WebSocket) {
				socket = new WebSocket(addreses);
				socket.onmessage = function (event) {
					var ta = document.getElementById('chatContent');
					ta.value = ta.value + '\n' + event.data
				};
				socket.onopen = function (event) {
					var ta = document.getElementById('chatContent');
					ta.value = "连接开启!";
					
					document.getElementById('btnconn').value="断开"
				};
				socket.onclose = function (event) {
					var ta = document.getElementById('chatContent');
					ta.value = ta.value + "连接被关闭";
					
					document.getElementById('btnconn').value="连接"
				};
			} else {
				alert("浏览器不支持 WebSocket！");
			}
		}
	};
	
	function disconnect() {
		if (!window.WebSocket) {
            return;
        }
        if (socket && socket.readyState == WebSocket.OPEN) {
			socket.close();
		} 
	};
    
 
    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("连接没有开启.");
        }
    }
</script>
<form onsubmit="return false;">
<h1>WebSocket聊天室</h1>
<input type="text" id="address" value="ws://127.0.0.1:96/Api/chat?name=xjh2&to=xjh1" style="width: 400px"/>
<input type="button" id="btnconn" value="连接" onclick="connect()"/>

<textarea id="chatContent" style="width: 100%; height: 400px;">
</textarea>

<hr/>
<input type="text" name="message" style="width: 300px"/>
<input type="button" value="发送消息" onclick="send(this.form.message.value)"/>
<input type="button" onclick="javascript:document.getElementById('chatContent').value=''" value="清空记录"/>
</form>
</body>
</html>